package com.xueke.crawler.helper;

import org.apache.commons.io.FileUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * Created by weibo on 2017/5/13.
 *
 * @author weibo.qin
 * @version 2017/5/13
 */
public class ProxyHelper {


    public static String parseDownloadUrl(String url, String docId, String userName, String password, int proxy,Map<String,String> cookiesFill) throws
        NumberFormatException, IOException {

        if (proxy == 0) return parseNormal(docId, userName, password,cookiesFill);

        return parseSuper(docId, userName, password,cookiesFill);
    }

    private static String parseNormal(String docId, String userName, String password,Map<String,String> cookiesFill) throws IOException {
        String url;
        url = "http://www.zxxk.com/soft/" + docId + ".html";
        Map<String, String> cookies = loginReturnCookie2(userName, password);
        String userId = cookies.get("xk.passport.uid");

        String softUrl = "http://soft.download.zxxk" +
            ".com/download/getscripts?softids=" + docId + "&userid=" + userId + "&iscart=0&source=0&ext=null&r" +
            "=0.18412359699188663";

        Connection.Response resp = Jsoup.connect(softUrl).method(Connection.Method.GET).execute();
        Map<String, String> cookies2 = resp.cookies();
        for (String key : cookies.keySet()) {
            System.out.println(key + "=" + cookies.get(key));
        }
        cookies.putAll(cookies2);
        cookiesFill.putAll(cookies) ;
        Document document = Jsoup.connect(softUrl).followRedirects(false).userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36").cookies(cookies).get();
        String script = document.text();
        script = script.replace("window.location", "returnUrl");
        script = "var resturnUrl;" + script;
        String tmp = "";
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("js");
            engine.eval(script);
            tmp = engine.eval("returnUrl").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(tmp);
        Document document2 = Jsoup.connect(tmp).followRedirects(false).userAgent("Mozilla/5.0 (Macintosh; " +
            "Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36").cookies(cookies).get();
        System.out.println(document2);
        String url2 = document2.select("a").first().attr("href");

        System.out.println(url2);
        String result = HTTPCommonUtil.getStringBody(url2, 10000, cookies, createIp());
        System.out.println(result);
        if (result.contains("账号已被锁定")) {
            return "-9999";
        }

        if (result.contains("或未找到资料")) {
            return "-9998";
        }

        Document document3 = Jsoup.parse(result);

//        Document document3 = Jsoup.connect(url2).followRedirects(false).userAgent("Mozilla/5.0 (Macintosh; " +
//            "Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36").cookies(cookies).get();
        return document3.select("a").first().attr("href");
    }


    public static String parseSuper(String docId, String userName, String password,Map<String,String> cookiesFill) throws IOException {
        String url;
        url = "http://www.zxxk.com/soft/" + docId + ".html";
        Map<String, String> cookies = loginReturnCookie2(userName, password);
        String userId = cookies.get("xk.passport.uid");

        String softUrl = "http://soft.download.zxxk" +
            ".com/download/getscripts?softids=" + docId + "&userid=" + userId + "&iscart=0&source=0&ext=null&r" +
            "=0.18412359699188663";

        Connection.Response resp = Jsoup.connect(softUrl).method(Connection.Method.GET).execute();
        Map<String, String> cookies2 = resp.cookies();
        for (String key : cookies.keySet()) {
            System.out.println(key + "=" + cookies.get(key));
        }
        cookies.putAll(cookies2);
        cookiesFill.putAll(cookies) ;

        Document document = Jsoup.connect(softUrl).followRedirects(false).userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36").cookies(cookies).get();
        String script = document.text();
        script = script.replace("window.location", "returnUrl");
        script = "var resturnUrl;" + script;
        String tmp = "";
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("js");
            engine.eval(script);
            tmp = engine.eval("returnUrl").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(tmp);
        Document document2 = Jsoup.connect(tmp).followRedirects(false).userAgent("Mozilla/5.0 (Macintosh; " +
            "Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36").cookies(cookies).get();
        String url2 = document2.select("a").first().attr("href");

        System.out.println(url2);

        String ip;
        if (userName.equalsIgnoreCase("qthgjzx01")) {
            ip = "221.211.197.128";
        } else if (userName.equalsIgnoreCase("ahgdfz")) {
            ip = "220.179.214.232";
        } else {
            ip = createIp();
        }

        String result = HTTPCommonUtil.getStringBody(url2, 10000, cookies, ip);
        System.out.println(result);
        System.out.println(result);
        if (result.contains("账号已被锁定")) {
            return "-9999";
        }
        Document document3 = Jsoup.parse(result);
//        Document document3 = Jsoup.connect(url2).followRedirects(false).header("X-Forwarded-For",ip).userAgent("Mozilla/5.0 " +
//            "(Macintosh; " +
//            "Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36").cookies(cookies).get();


        return document3.select("a").first().attr("href");
    }

    static Map<String, Map<String, String>> cookieMap = new HashMap<String, Map<String, String>>();


    public static Map<String, String> loginReturnCookie2(String userName,
                                                         String password) {
        if (cookieMap.containsKey(userName)) return cookieMap.get(userName);
        Map<String, String> params = new HashMap<String, String>();
        params.put("Action", "chk");
        params.put("Ajax", "1");
        params.put("UserPass", password);
        params.put("UserName", userName);
        params.put("Type", "1");

        Connection.Response resp;
        try {
            String url = "https://sso.zxxk.com/login";
            Document doc = Jsoup.connect(url).get();

            String lt = doc.select("input[name=lt]").val();
            String execution = doc.select("input[name=execution]").val();
            String _eventId = doc.select("input[name=_eventId]").val();
            System.out.println(lt);
            System.out.println(execution);
            System.out.println(_eventId);

            String u = String.format("%s?username=%s&password=%s&lt=%s&execution=%s&_eventId=%s", url, userName, password, lt, execution, _eventId);

            resp = Jsoup.connect(u).method(Connection.Method.POST).execute();
            Map<String, String> cookies = resp.cookies();
            for (String key : cookies.keySet()) {
                System.out.println(key + "=" + cookies.get(key));
            }
            cookieMap.put(userName, resp.cookies());
            return resp.cookies();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    public static void main(String[] args) throws IOException {
        String userName = "215chen";
        String password = "chen215";

        String docId = "6595593";
        String url = "http://www.zxxk.com/soft/" + docId + ".html";

        Map<String, String> cookies = loginReturnCookie2(userName, password);
        String userId = cookies.get("xk.passport.uid");

        String softUrl = "http://soft.download.zxxk" +
            ".com/download/getscripts?softids=" + docId + "&userid=" + userId + "&iscart=0&source=0&ext=null&r" +
            "=0.18412359699188663";

        Connection.Response resp = Jsoup.connect(softUrl).method(Connection.Method.GET).execute();
        Map<String, String> cookies2 = resp.cookies();
        for (String key : cookies.keySet()) {
            System.out.println(key + "=" + cookies.get(key));
        }
        cookies.putAll(cookies2);

        Document document = Jsoup.connect(softUrl).followRedirects(false).userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36").cookies(cookies).get();
        String script = document.text();
        script = script.replace("window.location", "returnUrl");
        script = "var resturnUrl;" + script;
        String tmp = "";
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("js");
            engine.eval(script);
            tmp = engine.eval("returnUrl").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(tmp);
        Document document2 = Jsoup.connect(tmp).followRedirects(false).userAgent("Mozilla/5.0 (Macintosh; " +
            "Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36").cookies(cookies).get();

        System.out.println(document2);

        String url2 = document2.select("a").first().attr("href");

        System.out.println(url2);

        Connection.Response response = HTTPCommonUtil.getResponse(url2, 10000, cookies, createIp());
    //    System.out.println(response.cookies().toString());
    //    cookies2.putAll(response.cookies());
        System.out.println(response.header("Location"));
        String url3 = response.header("Location");
        //Document document3 = Jsoup.parse(result);
        HttpUtil.download(url3, "d:/test2018.ppt",cookies);
       // Connection.Response response1 = Jsoup.connect(url3).cookies(cookies).ignoreContentType(true).execute();
       // FileUtils.writeByteArrayToFile(new File("d:/test2018.ppt"),response1.bodyAsBytes());
        /*Document document3 = Jsoup.connect(url2).followRedirects(false).userAgent("Mozilla/5.0 (Macintosh; " +
            "Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36").cookies(cookies).get();

        System.out.println(document3);

        HttpUtil.download(document3.select("a").first().attr("href"), "/Users/weibo/temp/test2017.doc");
*/
    }

    public static String createIp() {
        Random random = new Random();
        String ip = String.format("%s.%s.%s.%s", String.valueOf(random.nextInt(255)), String.valueOf(random.nextInt(255)), String.valueOf(random.nextInt(255)), String.valueOf(random.nextInt(255)));
        System.out.println("生成伪装ip: " + ip);
        return ip;
    }


}
